package com.ruoyi.file.service;

import java.io.InputStream;
import java.util.Locale;
import java.util.UUID;

import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.alibaba.nacos.common.utils.IoUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.file.config.MinioConfig;
import com.ruoyi.file.utils.FileUploadUtils;

/**
 * Minio 文件存储
 *
 * @author ruoyi
 */
@Primary
@Service
public class MinioSysFileServiceImpl implements ISysFileService
{
    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private MinioClient client;



    /**
     * Minio文件上传接口
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception
    {
        InputStream inputStream = null;
        boolean bucketExists = client.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucketName())
                .build());
        if (!bucketExists) {
            client.makeBucket(MakeBucketArgs.builder().bucket(minioConfig.getBucketName()).build());
            client.setBucketPolicy(SetBucketPolicyArgs.builder().bucket(minioConfig.getBucketName()).config(this.createBucketPolicyConfig(minioConfig.getBucketName())).build());
        }
        try
        {
            String fileName = FileUploadUtils.extractFilename(file);
            inputStream = file.getInputStream();
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(minioConfig.getBucketName())
                    .object(fileName)
                    .stream(inputStream, file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build();
            client.putObject(args);

            return minioConfig.getUrl() + "/" + minioConfig.getBucketName() + "/" + fileName;
        }
        catch (Exception e)
        {
            throw new RuntimeException("Minio Failed to upload file", e);
        }
        finally
        {
            IoUtils.closeQuietly(inputStream);
        }
    }



    /**
     * 上传文件到 MinIO
     * @param file 上传的文件
     * @return 文件的完整访问 URL（如 http://localhost:9000/images/xxx.jpg）
     * @throws Exception 上传失败时抛出异常
     */
    public     String upload(MultipartFile file) throws Exception {
        // 1. 参数校验
        if (file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }

        // 2. 生成安全文件名（防止重复和路径遍历）
        String originalFilename = file.getOriginalFilename();
        if (originalFilename == null) {
            throw new IllegalArgumentException("文件名无效");
        }
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String safeFilename = UUID.randomUUID().toString() + fileExtension;

        // 3. 初始化 MinIO 客户端
        MinioClient minioClient = MinioClient.builder()
                .endpoint(minioConfig.getUrl())
                .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey())
                .build();

        // 4. 确保存储桶存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioConfig.getBucketName()).build());
        if (!found) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioConfig.getBucketName()).build());
        }

        // 5. 上传文件
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(minioConfig.getBucketName())
                        .object(safeFilename)  // 对象名称（即 MinIO 中的路径）
                        .stream(file.getInputStream(), file.getSize(), -1)
                        .contentType(file.getContentType())
                        .build()
        );

        // 6. 生成访问 URL（假设存储桶是公开的）
        return String.format("%s/%s/%s", minioConfig.getUrl(),  minioConfig.getBucketName(), safeFilename);

        // 如果存储桶是私有的，使用预签名 URL（有效期 24 小时）：
        // return minioClient.getPresignedObjectUrl(
        //     GetPresignedObjectUrlArgs.builder()
        //         .bucket(BUCKET_NAME)
        //         .object(safeFilename)
        //         .method(Method.GET)
        //         .expiry(24, TimeUnit.HOURS)
        //         .build()
        // );
    }



    /**
     * Minio文件删除接口
     * 
     * @param fileUrl 文件访问URL
     * @throws Exception
     */
    @Override
    public void deleteFile(String fileUrl) throws Exception
    {
        try
        {
            String minioFile = StringUtils.substringAfter(fileUrl, minioConfig.getBucketName());
            client.removeObject(RemoveObjectArgs.builder().bucket(minioConfig.getBucketName()).object(minioFile).build());
        }
        catch (Exception e)
        {
            throw new RuntimeException("Minio Failed to delete file", e);
        }
    }

    private String createBucketPolicyConfig(String bucketName) {
        return "{\n" +
                "  \"Statement\" : [ {\n" +
                "    \"Action\" : \"s3:GetObject\",\n" +
                "    \"Effect\" : \"Allow\",\n" +
                "    \"Principal\" : \"*\",\n" +
                "    \"Resource\" : \"arn:aws:s3:::%s/*\"\n" +
                "  } ],\n" +
                "  \"Version\" : \"2012-10-17\"\n" +
                "}".format(Locale.ROOT, bucketName);
    }



}
